package com.sparrow.actor;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 抽象的actor,每个actor都有一个信箱
 */
public abstract class AbstractActor {

    /**
     * 信箱
     */
    private MailBox mailBox = new MailBox();

    /**
     * 执行器
     */
    private Executor executor;

    public AbstractActor(Executor executor) {
        this.executor = executor;
    }


    /**
     * 投递消息,默认异步执行
     * @param msg
     */
    public void tell(Runnable msg) {
        tell(msg, this.executor, false);
    }

    /**
     * 投递消息,默认异步执行
     * @param msg
     */
    public void tell(Runnable msg, boolean sync) {
        tell(msg, this.executor, sync);
    }

    /**
     * 投递消息
     * @param msg
     * @param executor 指定的执行器
     * @param sync 是否同步
     */
    public void tell(Runnable msg, Executor executor, boolean sync) {
        if (sync) {
            msg.run();
        } else {
            mailBox.enqueue(msg, executor != null ? executor : this.executor);
        }
    }


}
